package com.letfox.redis.util;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SetOperationUtil<T> {

	@Resource(name = "redisTemplate")
	private RedisTemplate<String, T> redisTemplate;

	/**
	 * 
     * 缓存Set
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return  缓存数据的对象
	 */
	public BoundSetOperations<String, T> setCacheSet(String key, Set<T> set) {
		BoundSetOperations<String,T> operations = redisTemplate.boundSetOps(key);
		Iterator<T> it = set.iterator();
		while (it.hasNext()) {
			operations.add(it.next());
		}
		return operations;
	}
	
	/**
     * 获得缓存的set
     * @param key 缓存键值
     * @return 获取Set数据
	 */
	public Set<T> getCacheSet(String key){
		Set<T> set = new HashSet<T>();
		BoundSetOperations<String,T> operations = redisTemplate.boundSetOps(key);
		Long size = operations.size();
		for (int i = 0; i < size; i++) {
			set.add(operations.pop());
		}
		return set;
	}
}
